"use strict";
import * as React from 'react';
const { StyleSheet, View, DeviceEventEmitter } = require('react-native');
const { Router, Scene, Reducer, Modal, Actions } = require('react-native-router-flux');
const { connect } = require('react-redux');
const moment = require('moment');
const appConfig = require('../app.json');
import Member from "./routers/member/index";
import CommunityPage from "./routers/community/index";
import ReservePage from "./routers/reserve/Reserve";
import MessagePage from "./routers/message/Message";
import MyIcon from "./component/icon";
import { ISIPHONE_X, NAVBAR_HEIFHT, TABBAR_HEIFHT } from "./constant";
import GuidePage from "./routers/Guide";
import LaunchPage from "./routers/Launch";
import LoginPage from "./routers/auth/Login";
import ForgetPwd from "./routers/auth/ForgetPwd";
import Place from "./routers/place/Place";
import CreateArchivesPage from "./routers/archives/CreateArchives";
import AreaPickPage from "./routers/archives/AreaPick";
import FocusPage from "./routers/archives/Focus";
import SearchPage from "./routers/search/Search";
import NewPostingsPage from "./routers/community/NewPostings";
import MyImagePicker from "./component/MyImagePicker";
import PostingsDetailPage from "./routers/community/PostingsDetail";
import AllGroupsPage from "./routers/community/AllGroups";
import ActiveFilterPage from "./routers/community/ActiveFilter";
import ActiveDetailPage from "./routers/community/ActiveDetail";
import RemindPage from "./routers/remind/Remind";
import RepeatPage from "./routers/remind/Repeat";
import CustomRepeatPage from "./routers/remind/CustomRepeat";
import MyActivesPage from "./routers/community/MyActives";
import GroupDetailPage from "./routers/community/GroupDetail";
import GroupInfoDetailPage from "./routers/community/GroupInfoDetail";
import MyPlaceDetailPage from "./routers/place/MyPlaceDetail";
import GuestRegisterPage from "./routers/place/GuestRegister";
import SupportPage from "./routers/place/Support";
import SupportReportPage from "./routers/place/SupportReport";
import BuildingGuidePage from "./routers/place/BuildingGuide";
import ConvenientInfoPage from "./routers/place/ConvenientInfo";
import PlaceExtraIntroducePage from "./routers/place/PlaceExtraIntroduce";
import T from "./utils/T";
import ActivePage from "./routers/place/Active";
import ReserveWorkSpacePage from "./routers/reserve/ReserveWorkSpace";
import NoticePage from "./routers/community/Notice";
import UserProfilePage from "./routers/user/UserProfile";
import ColleagueListPage from "./routers/user/ColleagueList";
import PrinterUsagePage from "./routers/user/PrinterUsage";
import InvoiceListPage from "./routers/user/InvoiceList";
import InvoiceDetailPage from "./routers/user/InvoiceDetail";
import ConfigNoticePage from "./routers/user/ConfigNotice";
import ChangePasswordPage from "./routers/user/ChangePassword";
import AboutPage from "./routers/user/About";
import PrinterUsageHistoryPage from "./routers/user/PrinterUsageHistory";
import constant from "./utils/constant";
import ChatPage from "./routers/message/Chat";
import Request from "./utils/Request";
import NewMessagePage from "./routers/message/NewMessage";
import ConfirmReservePage from "./routers/reserve/ConfirmReserve";
import MeetingDescriptionPage from "./routers/reserve/MeetingDescription";
import AddHobbyOrSkillPage from "./routers/archives/AddHobbyOrSkill";
import WebPage from "./routers/others/Web";
import ContactSelectPage from "./routers/others/ContactSelect";
import ConfirmReportPage from "./routers/place/ConfirmReport";
import { toastValidateError } from "./utils/tools";
import CompanyInfoPage from "./routers/user/CompanyInfo";
import { NetUtil } from "./utils/NetUtil";
import Eq from "./utils/Eq";
const Stomp = require('webstomp-client');
const TabIcon = (props) => {
    return (<View style={{ position: 'absolute' }}>
            <MyIcon {...props} name={props.image} size={25} color={props.focused ? "#252728" : '#999999'}/>
        </View>);
};
const Styles = StyleSheet.create({
    tabBarSelectedItemStyle: {
        backgroundColor: '#fff',
        color: '#f00'
    },
    tabBarStyle: {
        height: TABBAR_HEIFHT,
        paddingBottom: ISIPHONE_X ? 20 : 0,
    },
    navigationBarStyle: {
        height: NAVBAR_HEIFHT,
    },
    icon: {
        width: 19,
        height: 20
    }
});
const defaultProps = {
    hideTabBar: false,
    tabs: true,
    showLabel: true,
    swipeEnabled: false,
    hideNavBar: true,
    tabBarPosition: 'bottom',
    animationEnabled: false,
    tabBarSelectedItemStyle: Styles.tabBarSelectedItemStyle,
    tabBarStyle: Styles.tabBarStyle,
    activeTintColor: '#252728',
    inactiveTintColor: '#999999',
    navigationBarStyle: Styles.navigationBarStyle,
    titleStyle: {
        color: '#333',
    },
};
const reducerCreate = params => {
    const defaultReducer = new Reducer(params);
    return (state, action) => {
        return defaultReducer(state, action);
    };
};
class RouterComponent extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            badgeNumbers: {
                community: 0,
                message: 0,
                place: 0,
                reserve: 0,
                member: 0
            }
        };
        this.onConnect = (e) => {
            this.subscript();
        };
        this.subscript = () => {
            if (Eq.eq(this.WaitSubscriptUrls, this.SubscriptUrls)) {
                alert("1");
                return;
            }
            else {
                this.WaitSubscriptUrls.map(url => {
                    if (this.SubscriptUrls.indexOf(url) === -1) {
                        let subscription = null;
                        console.log(url, constant.subscriptNoticeUrl);
                        if (url === constant.subscriptNoticeUrl) {
                            subscription = this.Socket.subscribe(url, this.onNotice);
                        }
                        else {
                            subscription = this.Socket.subscribe(url, this.onMessage);
                        }
                        this.SubscriptUrls.push(url);
                        this.Subscriptions[url] = subscription;
                    }
                });
                this.WaitSubscriptUrls = [];
            }
        };
        this.onSend = (e) => {
            if (this.Socket && this.Socket.connected) {
                const url = constant.subscriptMessageUrl + `-${e.sender}`;
                if (this.SubscriptUrls.indexOf(url) !== -1) {
                    const message = {
                        type: 'text',
                        content: e.message.text,
                        sender: e.sender,
                        nickname: e.nickname,
                        toType: 'USER',
                        receiver: e.receiver
                    };
                    this.Socket.send(constant.socketSendMessageUrl, JSON.stringify(message), {
                        subscription: 'false',
                    });
                    this.props.dispatch({
                        type: 'chat/sendMessage',
                        payload: { message: e.message, origin: message, save: true }
                    });
                    this.props.dispatch({
                        type: 'chat/contact',
                        payload: {
                            senderId: e.receiverId,
                            receiverId: e.senderId
                        }
                    });
                }
            }
        };
        this.onNotice = (e) => {
            const message = JSON.parse(e.body);
            let badgeNumbers = this.state.badgeNumbers;
            badgeNumbers.community++;
            this.setState({ badgeNumbers });
        };
        this.onMessage = (e) => {
            const message = JSON.parse(e.body);
            if (!message)
                return;
            Request.log('收到消息', e, Actions.currentScene);
            let badgeNumbers = this.state.badgeNumbers;
            badgeNumbers.message++;
            this.setState({ badgeNumbers });
            const scene = Actions.currentScene;
            const giftedChatMessageItem = {
                _id: moment().format('x') + '-' + message.nickname,
                text: message.content,
                createdAt: moment().toDate(),
                user: {
                    _id: message.nickname,
                    name: message.nickname,
                    avatar: message.avatar ? message.avatar : ''
                }
            };
            switch (scene) {
                case 'chat':
                    {
                        this.props.dispatch({
                            type: 'chat/sendMessage',
                            payload: { message: giftedChatMessageItem, save: false }
                        });
                    }
                    break;
                default:
                    {
                        this.props.dispatch({
                            type: 'message/newMessage',
                            payload: Object.assign({}, message)
                        });
                    }
                    break;
            }
        };
        this.onError = (e) => {
            toastValidateError(null, '服务器断开,重新连接!!\n' + e.message);
            if (this.Socket) {
                setTimeout(_ => {
                    this.WaitSubscriptUrls = this.SubscriptUrls;
                    this.Socket.connect(constant.socketHeaders, this.onConnect, this.onError);
                }, 10 * 1000);
            }
        };
        this.onSubscript = (e) => {
            if (!e)
                return;
            if (this.Socket) {
                let url = constant.subscriptMessageUrl + `-${e.sender}`;
                if (e.subscriptUrl) {
                    url = e.subscriptUrl;
                }
                const waitIndex = this.WaitSubscriptUrls.indexOf(url);
                if (this.Socket.connected) {
                    if (this.SubscriptUrls.indexOf(url) === -1) {
                        let subscription = null;
                        if (e.subscriptUrl) {
                            console.log(1);
                            subscription = this.Socket.subscribe(url, this.onNotice);
                        }
                        else {
                            console.log(1);
                            subscription = this.Socket.subscribe(url, this.onMessage);
                        }
                        this.SubscriptUrls.push(url);
                        this.Subscriptions[url] = subscription;
                    }
                    if (waitIndex !== -1) {
                        this.WaitSubscriptUrls.slice(waitIndex, 1);
                    }
                }
                else {
                    if (this.WaitSubscriptUrls.indexOf(url) === -1) {
                        this.WaitSubscriptUrls.push(url);
                    }
                }
            }
        };
        this.onRemoveSubscript = (e) => {
            if (!e)
                return;
            if (this.Socket && this.Socket.connected) {
                const url = constant.subscriptMessageUrl + `-${e.receiver}`;
                if (this.SubscriptUrls.indexOf(url) !== -1) {
                    this.SubscriptUrls.splice(this.SubscriptUrls.indexOf(url), 1);
                    this.Subscriptions[url].unsubscribe();
                    delete this.Subscriptions[url];
                }
            }
        };
        this.removeAllSubscript = () => {
            this.SubscriptUrls.map(url => {
                this.Subscriptions[url].unsubscribe();
                delete this.Subscriptions[url];
            });
            this.SubscriptUrls = [];
        };
        this.onEnter = (sceneKey) => {
            Request.log(`%c onEnter`, 'color:green', sceneKey);
            let badgeNumbers = this.state.badgeNumbers;
            switch (sceneKey) {
                case 'community':
                    {
                        badgeNumbers.community = 0;
                        this.setState({ badgeNumbers });
                        this.props.dispatch({ type: 'auth/freshUserInfo' });
                        DeviceEventEmitter.emit(constant.noticeKeyOfEnterCommunity);
                    }
                    break;
                case 'place': {
                    badgeNumbers.place = 0;
                    this.setState({ badgeNumbers });
                    this.props.dispatch({ type: 'place/fetchAreaUser' });
                    break;
                }
                case 'member': {
                    badgeNumbers.member = 0;
                    this.setState({ badgeNumbers });
                    this.props.dispatch({ type: 'auth/freshUserInfo' });
                    break;
                }
                case 'message': {
                    badgeNumbers.message = 0;
                    this.setState({ badgeNumbers });
                    this.props.dispatch({ type: 'chat/fetchFriends' });
                    break;
                }
            }
        };
        this.SubscriptUrls = [];
        this.Subscriptions = {};
        this.WaitSubscriptUrls = [];
    }
    componentDidMount() {
        this.Socket = Stomp.client(constant.socketUrl, {
            debug: appConfig.debug,
            heartbeat_in: 0,
            heartbeat_out: 0,
        });
        this.Socket.connect(constant.socketHeaders, this.onConnect, this.onError);
        DeviceEventEmitter.addListener(constant.noticeKeyOfSubscriptMessage, this.onSubscript);
        DeviceEventEmitter.addListener(constant.noticeKeyOfSendMessage, this.onSend);
        NetUtil.registerNetworkStateListener(state => {
            this.netState = state;
        }, change_state => {
            this.netState = change_state;
        });
    }
    componentWillUnmount() {
        DeviceEventEmitter.removeListener(constant.noticeKeyOfSubscriptMessage);
        DeviceEventEmitter.removeListener(constant.noticeKeyOfSendMessage);
        this.removeAllSubscript();
    }
    render() {
        return (<Router getSceneStyle={getSceneStyle} createReducer={reducerCreate}>
                <Modal panHandlers={null}>
                    <Scene key='root'>
                        <Scene {...defaultProps} key='tab' initial>
                            
                            <Scene key="community" component={CommunityPage} title="社区" tabBarLabel={T('tab.tab1')} hideNavBar onEnter={this.onEnter.bind(this, 'community')} icon={TabIcon} badgeNumber={this.state.badgeNumbers.community} image='icon-icon5fuzhi'/>

                            
                            <Scene key="place" component={Place} title={T('tab.tab2')} tabBarLabel={T('tab.tab2')} hideNavBar onEnter={this.onEnter.bind(this, 'place')} icon={TabIcon} badgeNumber={this.state.badgeNumbers.place} image='icon-ditu1'/>

                            
                            <Scene key="reserve" component={ReservePage} title={T('tab.tab3')} tabBarLabel={T('tab.tab3')} hideNavBar icon={TabIcon} badgeNumber={this.state.badgeNumbers.reserve} image='icon-icon5fuzhi'/>

                            
                            <Scene key="message" component={MessagePage} title={T('tab.tab4')} tabBarLabel={T('tab.tab4')} hideNavBar onEnter={this.onEnter.bind(this, 'message')} icon={TabIcon} badgeNumber={this.state.badgeNumbers.message} image='icon-xiaoxi-copy'/>

                            
                            <Scene key="member" component={Member} title={T('tab.tab5')} tabBarLabel={T('tab.tab5')} hideNavBar icon={TabIcon} badgeNumber={this.state.badgeNumbers.member} onEnter={this.onEnter.bind(this, 'member')} image='icon-zhanghu'/>


                        </Scene>

                        <Scene key='launch' initial component={LaunchPage} hideNavBar hideTabBar/>

                        
                        <Scene key='guide' component={GuidePage} hideNavBar hideTabBar/>
                        <Scene key='web' component={WebPage} hideNavBar hideTabBar/>

                        <Scene key="forgetPwd" component={ForgetPwd} hideNavBar hideTabBar/>
                        <Scene key="search" component={SearchPage} hideNavBar hideTabBar/>
                        <Scene key="postingsDetail" component={PostingsDetailPage} hideNavBar hideTabBar/>
                        <Scene key="activeDetail" component={ActiveDetailPage} hideNavBar hideTabBar/>
                        <Scene key="myActives" component={MyActivesPage} hideNavBar hideTabBar/>
                        <Scene key="groupDetail" component={GroupDetailPage} hideNavBar hideTabBar/>
                        <Scene key="groupInfoDetail" component={GroupInfoDetailPage} hideNavBar hideTabBar/>
                        <Scene key="myPlaceDetail" component={MyPlaceDetailPage} hideNavBar hideTabBar/>
                        <Scene key="guestRegister" component={GuestRegisterPage} hideNavBar hideTabBar/>
                        <Scene key="support" component={SupportPage} hideNavBar hideTabBar/>
                        <Scene key="supportReport" component={SupportReportPage} hideNavBar hideTabBar/>
                        <Scene key="buildingGuide" component={BuildingGuidePage} hideNavBar hideTabBar/>
                        <Scene key="convenientInfo" component={ConvenientInfoPage} hideNavBar hideTabBar/>
                        <Scene key="placeExtraIntroduce" component={PlaceExtraIntroducePage} hideNavBar hideTabBar/>
                        <Scene key="active" title={T('active')} component={ActivePage} hideNavBar hideTabBar/>
                        <Scene key="reserveWorkSpace" component={ReserveWorkSpacePage} hideNavBar hideTabBar/>
                        <Scene key="notice" component={NoticePage} hideNavBar hideTabBar/>
                        <Scene key="userProfile" component={UserProfilePage} hideNavBar hideTabBar/>
                        <Scene key="printerUsage" title='打印用法' component={PrinterUsagePage} hideNavBar hideTabBar/>
                        <Scene key="printerUsageHistory" title='打印记录' component={PrinterUsageHistoryPage} hideNavBar hideTabBar/>
                        <Scene key="invoiceList" title='查看发票' component={InvoiceListPage} hideNavBar hideTabBar/>
                        <Scene key="invoiceDetail" title='发票详情' component={InvoiceDetailPage} hideNavBar hideTabBar/>
                        <Scene key="configNoticePage" title='配置通知' component={ConfigNoticePage} hideNavBar hideTabBar/>
                        <Scene key="changePassword" title='修改密码' component={ChangePasswordPage} hideNavBar hideTabBar/>
                        <Scene key="about" title='关于' component={AboutPage} hideNavBar hideTabBar/>
                        <Scene key="chat" title='聊天' component={ChatPage} hideNavBar hideTabBar/>
                        <Scene key="newMessage" title='新消息' component={NewMessagePage} hideNavBar hideTabBar/>
                        <Scene key="confirmReserve" title='确定预定房间' component={ConfirmReservePage} hideNavBar hideTabBar/>
                        <Scene key="meetingDescription" title='说明' component={MeetingDescriptionPage} hideNavBar hideTabBar/>
                        <Scene key="createArchives" component={CreateArchivesPage} hideNavBar hideTabBar/>
                        <Scene key="addHobbyOrSkill" component={AddHobbyOrSkillPage} hideNavBar hideTabBar/>
                        <Scene key="companyInfo" component={CompanyInfoPage} hideNavBar hideTabBar/>
                        <Scene key="archives">
                            <Scene key="editArchives" component={CreateArchivesPage} hideNavBar hideTabBar/>
                            <Scene key="areaPick" component={AreaPickPage} hideNavBar hideTabBar/>
                            <Scene key="focus" component={FocusPage} hideNavBar hideTabBar/>
                        </Scene>
                    </Scene>

                    

                    <Scene key="newPostings" component={NewPostingsPage} hideNavBar hideTabBar/>
                    <Scene key="myImagePicker" component={MyImagePicker} hideNavBar hideTabBar/>
                    <Scene key="allGroups" component={AllGroupsPage} hideNavBar hideTabBar/>
                    <Scene key="activeFilter" component={ActiveFilterPage} hideNavBar hideTabBar/>
                    <Scene key="colleagueList" component={ColleagueListPage} hideNavBar hideTabBar/>
                    <Scene key="selectContact" component={ContactSelectPage} hideNavBar hideTabBar/>
                    <Scene key="confirmReport" component={ConfirmReportPage} hideNavBar hideTabBar/>

                    <Scene key="auth">
                        <Scene key="login" component={LoginPage} hideNavBar hideTabBar initial/>
                        <Scene key="forgetPwd" component={ForgetPwd} hideNavBar hideTabBar/>
                    </Scene>
                    <Scene key="remind">
                        <Scene key="newRemind" component={RemindPage} hideNavBar hideTabBar/>
                        <Scene key="repeat" component={RepeatPage} hideNavBar hideTabBar/>
                        <Scene key="customRepeat" component={CustomRepeatPage} hideNavBar hideTabBar/>
                    </Scene>
                </Modal>

            </Router>);
    }
}
export default connect()(RouterComponent);
const getSceneStyle = function (props, computedProps) {
    return {
        display: 'flex',
        flex: 1,
        shadowColor: null,
        shadowOffset: null,
        shadowOpacity: null,
        shadowRadius: null,
        backgroundColor: 'white',
        paddingBottom: ISIPHONE_X ? 20 : 0
    };
};
